//
//  ApiErrorMiddleware.swift
//  hello
//
//  Created by yafei li on 2025/9/12.
//


import Vapor
import Foundation

// 错误处理中间件（更实用的例子）
struct ApiErrorMiddleware: AsyncMiddleware {
    func respond(to request: Request, chainingTo next: any AsyncResponder) async throws -> Response {
        do {
            return try await next.respond(to: request)
        } catch {
            // 捕获错误
            request.logger.report(error: error)
             
            let message: String?
            let code: Int 
            
            // 判断错误类型
            if let abort = error as? Abort {
                switch abort.status {
                case let .custom(code: c, reasonPhrase: r):
                            message = r
                            code = Int(c) // 使用 HTTP 状态码作为 code
                default:
                            message = abort.reason
                            code = Int(abort.status.code) // 使用 HTTP 状态码作为 code
                }
            }  else{
                message = "\(error)"
                code = 500
            }
            
            // 创建格式化的错误响应
            let errorResponse = ApiResponse<EmptyContent>(code: code, message: message, data: nil)
            // 构建 Response
            let response = Response()
            try response.content.encode(errorResponse, as: .json)
            return response
        }
    }
}

// 一个空内容类型，用于无数据返回的情况
struct EmptyContent: Content {}
